package com.yesep.learn.jwt.handler;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.access.AccessDeniedHandler;

import com.yesep.learn.jwt.common.R;
import com.yesep.learn.jwt.util.SecurityUtils;
import com.yesep.learn.jwt.util.ServletUtils;

import lombok.extern.slf4j.Slf4j;

/**
 * @Description: 自定义权限不足 需要做的业务操作 当用户登录系统后访问资源时因权限不足则会进入到此类并执行相关业务
 */
@Slf4j
public class AccessDeniedHandlerImpl implements AccessDeniedHandler {

	@Override
	public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException e) throws IOException, ServletException {
		Authentication auth = SecurityUtils.getAuthentication();
		if (auth != null) {
			log.warn("User: " + auth.getName() + " attempted to access the protected URL: " + request.getRequestURI());
		}
		response.setStatus(HttpServletResponse.SC_FORBIDDEN);
		ServletUtils.writeValueAsString(R.me(HttpServletResponse.SC_FORBIDDEN, e.getMessage()), response);
	}
}
